//
//  HJOAuthViewController.swift
//  zhangmiSinweibo
//
//  Created by zhangmi on 16/5/23.
//  Copyright © 2016年 Paramount Pictures. All rights reserved.
//

import UIKit
import SVProgressHUD
//设置偏好设置的key
private let userInfokey = "com.baidu.userInfoKey"

class HJOAuthViewController: UIViewController {
    
    //声明webView的属性
    let webView = UIWebView()
    
    
    override func loadView() {
        //在loadView阶段, 将跟视图替换为webView
        view = webView
        webView.opaque = false
        webView.backgroundColor = UIColor.whiteColor()

        //设置代理
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setNavBar()
        loadOauthPage()
        
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

    //打开授权页面
    private func loadOauthPage() {
        //获取req对象
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
    
        
        let url = NSURL(string: urlString)!
        let req = NSURLRequest(URL: url)
        webView.loadRequest(req)
    }
}


//设置导航条 监听按钮点击事件
extension HJOAuthViewController {
    
    //按钮的点击事件
    //CUICatalog: Invalid asset name supplied:  图片的名称使用了一个空的字符串
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        //使用webView 执行js 字符串
        //js 动态注入
        let jsString = "document.getElementById('userId').value = '15810987998', document.getElementById('passwd').value = 'hj123456' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    
    
    //完成导航条的设置
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: #selector(HJOAuthViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(HJOAuthViewController.testAccount))
    }
}


extension HJOAuthViewController: UIWebViewDelegate {
    //使用进度条展示加载的进度
    func webViewDidStartLoad(webView: UIWebView) {
        //显示用户等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    //授权成功之后, 就会回调新页面, 在回调页面的地址中会包含code(授权码)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //打印url
        let urlString = request.URL?.absoluteString ?? ""
        //截取收取成功的字符串中的code
        //定义授权成功的标记
        let successFlag = "code="
        if urlString.containsString(successFlag) {
            //授权成功
            // "!"表示程序员, 确保一定能够找到对应字符串所在的位置
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code,urlString)
            
            //获取code之后,应该使用xode码, 请求token(用户访问令牌)
//           loadAccessToken(code)
            
            HJUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                //闭包的参数需要生写
                if !isSuccess {
//                SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
                     SVProgressHUD.showErrorWithStatus(AppErrorTip)
 
                    return
                }
                
                //请求成功
                //SVProgressHUD.showSuccessWithStatus("登录成功")
                
//                UIApplication.sharedApplication().keyWindow?.rootViewController = HJWelcomeViewController()
//                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
                
                self.dismissViewControllerAnimated(false, completion: { 
                    //发出切换页面的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
                })
            })
            //不加载网页
           return false
        }
        return true
    }
}



